package crp.services.api.graphql.loaders;

import com.qwlabs.lang.C2;
import crp.core.academic.app.AcademicService;
import crp.core.academic.domain.models.AcademicTermEntity;
import crp.services.api.graphql.models.AcademicTermPayload;
import crp.services.api.graphql.models.AcademicYearPayload;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Source;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Set;

@GraphQLApi
@RequestScoped
public class AcademicYearPayloadLoader {
    private final AcademicService academicService;

    @Inject
    public AcademicYearPayloadLoader(AcademicService academicService) {
        this.academicService = academicService;
    }

    public List<@NotNull List<@NotNull AcademicTermPayload>> terms(@Source List<AcademicYearPayload> yearPayloads) {
        Set<Integer> years = C2.set(yearPayloads, AcademicYearPayload::getYear);
        Map<Integer, List<AcademicTermPayload>> terms = C2.listMap(
                academicService.searcher().termsByYears(years),
                AcademicTermEntity::getYear,
                AcademicTermPayload::of);
        return C2.list(yearPayloads,
                year -> terms.getOrDefault(year.getYear(), List.of()));

    }
}
